package com.ms.p2p.interceptor;


import com.ms.p2p.plugin.IPlugin;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.WebErrors;
import com.ms.p2p.plugin.validation.IValidate;
import com.ms.p2p.plugin.validation.ValidationBundle;
import com.ms.p2p.plugin.validation.annotation.Validations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


public class ValidationInterceptor implements HandlerInterceptor {
	@Autowired
	private ValidationBundle validationBundle;
	private static final String FRONT_ERROR = "/common/error";

	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		WebErrors errors = WebErrors.create();
		Map<String, String> decodedUriVariables = null;
		if(request.getRequestURI().equals("/")){
			response.sendRedirect("/index");
			return false;
		}

		HandlerMethod hm = (HandlerMethod) handler;


		Validations validations = hm.getMethodAnnotation(Validations.class);
		if(validations == null){
			return true;
		}
		Object obj = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
		if(obj != null){
			decodedUriVariables = (Map<String, String>) obj;
		}
		List<IPlugin> pluginList = validationBundle.getPluginList();
		for(IPlugin plugin : pluginList){
			IValidate validate = (IValidate) plugin;
			errors = validate.validate(request, errors, validations, decodedUriVariables);
		}
		if(errors.hasErrors()){
			if (AppContext.isAjax(request)) {
				errors.showErrorAjax(response);
			}else{
				request.setAttribute("errors", errors);
				request.getRequestDispatcher(FRONT_ERROR).forward(request, response);
			}
			return false;
		}
		return true;
	}
	

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}


	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
